/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: DefaultAjaxRedirectStrategy.java
 * 创  建  人: Roc Zheng (roc.djz@gmail.com)
 * 创建时间: 2017年8月2日 下午3:31:59
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.web.sys.security;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.DefaultRedirectStrategy;

import com.cpt.framework.web.util.HttpRequestUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * 
 * @since 1.0
 * @version 1.0
 * @author Roc Zheng (roc.djz@gmail.com)
 */
public class DefaultAjaxRedirectStrategy extends DefaultRedirectStrategy {
//  private ObjectMapper objectMapper;
//  
//  public void setObjectMapper(ObjectMapper objectMapper) {
//    this.objectMapper = objectMapper;
//  }
  
  /**
   * {@inheritDoc}
   */
  @Override
  public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {    
    if (HttpRequestUtils.isAjaxRequest(request)) {
      String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
      redirectUrl = response.encodeRedirectURL(redirectUrl);
      
      ObjectMapper objectMapper = new ObjectMapper();
      RespondedJson respondedJson = new RespondedJson();
      respondedJson.setStatus(response.getStatus());
      RespondedJsonHeaders headers = new RespondedJsonHeaders();
      headers.setLocation(redirectUrl);
      respondedJson.setHeaders(headers);      
      String json = objectMapper.writeValueAsString(respondedJson);
      
      if (logger.isDebugEnabled()) {
        logger.debug("AJAX Redirecting to '" + json + "'");
      }
      
      response.setStatus(HttpServletResponse.SC_OK);
      response.addHeader("X-Responded-JSON", json);
      return;
    }
    
    super.sendRedirect(request, response, url);
  }
}
